package controllers

import (
	"blog_api/db"
	"blog_api/models"
	"blog_api/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/keemi-zhou/validation"
	"strconv"
	"strings"
	"time"
)

type AdminController struct {
	BaseController
}

/**
 * AdminUserLogin
 * Author: Jazk-Z
 * @Description: 后台登录接口
 * @param c
 */
func (u *AdminController) AdminUserLogin(c *gin.Context) {
	username := strings.TrimSpace(c.Query("username"))
	password := strings.TrimSpace(c.Query("password"))
	valid := validation.Validation{}
	valid.Required(username, "用户名不能为空")
	valid.Required(password, "密码不能为空")

	if valid.HasErrors() {
		for _, err := range valid.Errors {
			u.error(c, err.Key, "")
			return
		}
	}

	where := fmt.Sprintf("username = '%s'", username)
	auinfo, err := models.AdminUserInfo(where)

	if err != nil {
		u.error(c, "该用户不存在", "")
		return
	}

	pwdtmp := utils.DoubleStrMerge(password, auinfo.Salt)
	passwordEncrypt := utils.Md5Encrypt(pwdtmp)
	if passwordEncrypt == auinfo.Password {
		token := utils.Md5Encrypt(strconv.Itoa(auinfo.Id))
		db.RedisSetInt(token, auinfo.Id, models.TOKEN_VALID_TIME)
		u.success(c, "登录成功", gin.H{
			"au":    auinfo.Username,
			"token": token,
			"id":    auinfo.Id,
		})
		return
	}
	u.error(c, "用户名或密码错误", "")
	return
}

/**
 * AdminDataPanel
 * @Description: 后台首页数据面板
 * @Author: Jazk-Z
 * @receiver u
 * @param c
 */
func (u *AdminController) AdminDataPanel(c *gin.Context) {
	data_panel := map[string]interface{}{
		"art_count":     models.ArtCount(),
		"date":          time.Now().Format("2006-01-02"),
		"go":            "go1.16.3",
		"sql":           "MySQL-5.7.34",
		"server":        "Nginx-1.18.0",
		"system":        "CentOS Linux release 7.7.1908 (Core)",
		"redis":         "6.2.6",
		"vue":           "2.5.2",
		"iview":         "4.0.0",
		"elasticsearch": "7.16.3-linux-x86_64",
	}
	u.success(c, "success", data_panel)
	return
}

/**
 * AdminLogout
 * @Description: 后台退出登录
 * @Author: Jazk-Z
 * @receiver u
 * @param c
 */
func (u *AdminController) AdminLogout(c *gin.Context) {
	auid, _ := c.Get("auid")
	token := utils.Md5Encrypt(fmt.Sprintf("%v", auid))
	res, err := db.RedisDel(token)
	fmt.Println("退出登录删除redis：", res, err)
	c.Set("auid", 0)

	u.success(c, "success_logout", "")
	return
}

/**
 * AdminLoginPwdEdit
 * @Description: 管理后台用户密码重置
 * @Author: Jazk-Z
 * @receiver u
 * @param c
 */
func (u *AdminController) AdminLoginPwdEdit(c *gin.Context) {
	new_password := strings.TrimSpace(c.Query("new_password"))
	confirm_password := strings.TrimSpace(c.Query("confirm_password"))
	login_user := strings.TrimSpace(c.Query("login_user"))
	old_password := strings.TrimSpace(c.Query("old_password"))

	valid := validation.Validation{}
	valid.Required(new_password, "新密码不能为空")
	valid.Required(confirm_password, "确认密码不能为空")
	valid.Required(login_user, "当前登录用户不能为空")
	valid.Required(old_password, "旧密码不能为空")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			u.error(c, err.Key, "")
			return
		}
	}

	if new_password != confirm_password {
		u.error(c, "两次密码输入不一致", "")
		return
	}

	where := fmt.Sprintf("username = '%s'", login_user)
	auinfo, err := models.AdminUserInfo(where)
	if err != nil {
		u.error(c, "该登录用户不存在", "")
		return
	}

	pwdtmp := utils.DoubleStrMerge(old_password, auinfo.Salt)
	passwordEncrypt := utils.Md5Encrypt(pwdtmp)
	if passwordEncrypt != auinfo.Password {
		u.error(c, "旧密码错误", "")
		return
	}

	new_salt := utils.GetRandomString(8)
	new_pwdtmp := utils.DoubleStrMerge(new_password, new_salt)
	new_passwordEncrypt := utils.Md5Encrypt(new_pwdtmp)
	data := make(map[string]interface{})
	data["password"] = new_passwordEncrypt
	data["salt"] = new_salt
	data["update_time"] = time.Now().Unix()
	auid, has := c.Get("auid")
	upd_where := ""
	if has {
		upd_where = fmt.Sprintf("id = %v and username = '%v'", auid, login_user)
	} else {
		upd_where = fmt.Sprintf("username = '%v'", login_user)
	}
	res := models.AdminUserUpdate(data, upd_where)
	if res == nil {
		u.success(c, "密码重置成功", "")
		return
	}
	u.error(c, "密码重置失败", "")
	return
}
